<template>
	<view class="root">
		<view
			v-for="(section, index) in model"
			:key="index"
			class="br-20 oh"
			:style="{ margin: `20rpx` }"
		>
			<block v-for="(option, key) in section" :key="key">
				<view v-if="option.el === 'swiper'">
					<swiper
						:indicator-dots="true"
						indicator-color="#eee"
						indicator-active-color="#fff"
					>
						<swiper-item
							v-for="(img, imgIndex) in option.value"
							:key="imgIndex"
							class="br-20"
							:style="{ width: `100%`, height: `280rpx` }"
						>
							<image
								class="width-100percent height-100percent"
								:src="img"
								mode="aspectFill"
								@click="operationImage(index, key, imgIndex)"
							/>
						</swiper-item>
						<swiper-item
							v-if="option.maxlength > option.value.length"
							class="br-20"
							:style="{ width: `100%`, height: `280rpx` }"
						>
							<image
								class="width-100percent height-100percent"
								src="/static/img/pic-addPhoto.png"
								mode="aspectFill"
								@click="chooseImage(index, key)"
							/>
						</swiper-item>
					</swiper>

					<!-- <text class="fs-28 mt-12">
						<text class="color-fa0707">*</text>
						<text class="color-333">建议banner尺寸：1065*420px</text>
					</text> -->
				</view>

				<label
					v-if="option.el === 'input'"
					class="height-90 pl-20 pr-20 bgc-fff"
					@click="operation(index, key)"
				>
					<text class="color-333 fs-30 fw-600">{{ option.title }}：</text>
					<input
						class="ml-30 fs-28 f1 input"
						:type="option.type"
						:placeholder="option.placeholder"
						:maxlength="option.maxlength"
						:disabled="!!option.disabled"
						:value="option.value"
						@input="inputValue($event, index, key)"
						placeholder-style="color: #999"
					/>

					<uni-icons v-if="option.disabled" type="arrowright" />
				</label>

				<view v-if="option.el === 'textarea'">
					<text class="color-333 fs-30 fw-600 pl-20 pr-20">{{ option.title }}：</text>
					<textarea
						class="mt-20 fs-28 fw-400 bgc-fff br-20"
						:style="{ height: `180rpx`, width: `auto`, padding: `20rpx` }"
						:maxlength="option.maxlength"
						:value="option.value"
						:placeholder="option.placeholder"
						@input="inputValue($event, index, key)"
						placeholder-style="color: #999"
					/>
				</view>
			</block>
		</view>

		<view
			:class="[
				`bgc-fff safe-area-inset-bottom content-box jc-center fixed bottom-0 width-100percent`,
			]"
			:style="{ height: `120rpx` }"
		>
			<button
				hover-class="tap-hover"
				:style="{
					margin: `0 24rpx`,
					backgroundImage: `linear-gradient(to right, #f45455, #ff7b6f)`,
				}"
				class="fs-34 color-fff fw-500 lh-90"
				@click="submit"
			>
				提交
			</button>
		</view>
	</view>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator";
	import { Storage, sleep } from "@/static/libs/utils";

	@Component
	export default class HomeSetting extends Vue {
		// component property
		homeConfig: AnyObject = {};
		get model(): AnyObject[] {
			const { homeConfig } = this;
			return [
				{
					banner: {
						el: "swiper",
						placeholder: "请上传首页轮播图",
						maxlength: 3,
						name: "arr_images",
						value: homeConfig.arr_images
							? JSON.parse(JSON.stringify(homeConfig.arr_images))
							: [],
						data: homeConfig.arr_images
							? JSON.parse(JSON.stringify(homeConfig.arr_images))
							: [],
					},
				},
				{
					storeName: {
						el: "input",
						title: "门店名称",
						maxlength: 9,
						type: "text",
						placeholder: "请输入门店名称",
						name: "store_name",
						data: homeConfig.store_name || "",
						value: homeConfig.store_name || "",
					},
					phoneNumber: {
						el: "input",
						title: "商家电话",
						maxlength: 11,
						type: "number",
						placeholder: "请输入商家电话",
						name: "phone",
						data: homeConfig.phone || "",
						value: homeConfig.phone || "",
					},
					address: {
						el: "input",
						title: "商家地址",
						maxlength: -1,
						type: "text",
						placeholder: "请选择商家地址",
						disabled: true,
						name: "address",
						value: homeConfig.address?.name || "",
						data: homeConfig.address ? JSON.stringify(homeConfig.address) : "",
					},
				},
				{
					notification: {
						el: "textarea",
						title: "公告栏",
						maxlength: 60,
						placeholder: "请输入公告内容...",
						name: "notice",
						data: homeConfig.notice || "",
						value: homeConfig.notice || "",
					},
				},
			];
		}

		onLoad() {
			uni.showToast({ title: "Loading", icon: "loading" });
			this.$request.get("/shop/homeConfig").then(({ data }) => {
				this.homeConfig = data || {};
				uni.hideLoading();
			});
		}

		async operation(index: number, key: string) {
			if (key !== "address") return;
			const option = this.model[index][key];
			const [chooseFail, locationRes]: any = await uni.chooseLocation({});
			if (chooseFail) return;
			option.value = locationRes.name;
			option.data = JSON.stringify(locationRes);
			this.$forceUpdate();
		}

		async operationImage(index: number, key: string, imgIndex: any) {
			const option = this.model[index][key];

			const [showFail, showRes]: any = await uni.showActionSheet({
				itemList: ["预览", "删除"],
			});
			if (showFail) return;
			!showRes.tapIndex
				? uni.previewImage({
						urls: option.value,
						current: imgIndex,
				  })
				: (option.value.splice(imgIndex, 1),
				  option.data.splice(imgIndex, 1),
				  this.$forceUpdate());
		}
		inputValue({ detail }: AnyObject, index: number, key: string) {
			const option = this.model[index][key];
			option.value = option.data = detail.value;
		}

		async chooseImage(index: number, key: string) {
			const option = this.model[index][key];
			const [chooseFail, chooseRes]: any = await uni.chooseImage({
				count: option.maxlength - option.value.length,
			});
			if (chooseFail) return;

			uni.showLoading({ title: "Loading..." });
			let i = 0;
			chooseRes.tempFilePaths.forEach(async (filePath: string) => {
				const [uploadFail, uploadRes]: any = await uni.uploadFile({
					url: this.$config.API_URL + "/common/upload",
					name: "file",
					filePath,
					formData: {
						// #ifdef MP-WEIXIN
						...uni.getAccountInfoSync().miniProgram,
						// #endif
					},
					header: { token: Storage.get("authorizationInfo")?.token },
				});
				if (uploadFail) {
					uni.showToast({ icon: "none", title: uploadFail.errMsg });
					return;
				}

				const { data, code, msg: title } = JSON.parse(uploadRes.data);
				if (code !== 1) {
					uni.showToast({ title, icon: "none" });
					return;
				}

				option.value.push(filePath);
				option.data.push(data.url);

				if (++i === chooseRes.tempFilePaths.length) {
					this.$forceUpdate();
					uni.hideLoading();
				}
			});
		}
		submit() {
			const flatModel: AnyObject = {};

			this.model.forEach((item) =>
				Object.keys(item).forEach((key) => (flatModel[key] = item[key]))
			);

			const params: AnyObject = {},
				verify = Object.values(flatModel).every((item) => {
					params[item.name] = item.data;
					item.name === "arr_image" && (item.data = item.data.toString());
					!item.data && uni.showToast({ title: item.placeholder, icon: "none" });
					return Boolean(item.data);
				});
			if (!verify) return;
			uni.showLoading({ title: "Loading...", mask: true });
			this.$request
				.post("/shop/homeSet", { id: this.homeConfig.id, ...params })
				.then(async ({ msg: title }) => {
					uni.showToast({ title, duration: 1000, mask: true });
					await sleep(1);
					uni.navigateBack({});
				});
		}
	}
</script>

<style lang="scss" scoped>
	// scss
</style>